package com.rsa.advice;

import com.rsa.utils.RSAUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.thymeleaf.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 参数解密
 */
public class MyHttpInputMessage implements HttpInputMessage {
    private HttpHeaders headers;

    private InputStream body;

    public MyHttpInputMessage(HttpInputMessage inputMessage, String privateKey) throws Exception {
        this.headers = inputMessage.getHeaders();
        String content = easpString(IOUtils.toString(inputMessage.getBody(), "utf-8"));
        this.body = IOUtils.toInputStream(RSAUtils.decryptDataOnJava(content, privateKey));
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }

    /**
     * @param requestData
     * @return
     */
    public String easpString(String requestData) {
        if (requestData != null && !requestData.equals("")) {
            String s = "{\"requestData\":";
            if (!requestData.startsWith(s)) {
                throw new RuntimeException("参数【requestData】缺失异常！");
            } else {
                int closeLen = requestData.length() - 1;
                int openLen = "{\"requestData\":".length();
                String substring = StringUtils.substring(requestData, openLen, closeLen);
                return substring;
            }
        }
        return "";
    }
}